package com.suneast.suneaststore.modules.store;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.common.GlideImageLoader;
import com.suneast.suneaststore.modules.goodsdetail.GoodsDetailFragment;
import com.suneast.suneaststore.modules.personal.order.fragment.FastOrderMaker;
import com.suneast.suneaststore.modules.store.adapter.StoreGoodsAdapter;
import com.suneast.suneaststore.bean.store.StoreCateBean;
import com.suneast.suneaststore.bean.store.StoreGoodsBean;
import com.suneast.suneaststore.modules.store.event.GotStoreCollectState;
import com.suneast.suneaststore.modules.store.event.GotStoreGoodsList;
import com.suneast.suneaststore.modules.store.event.GotStorePageData;
import com.suneast.suneaststore.modules.store.event.StoreCollectResult;
import com.suneast.suneaststore.modules.store.event.StoreRequestFail;
import com.suneast.suneaststore.ui.banner.Banner;
import com.suneast.suneaststore.ui.banner.BannerConfig;
import com.suneast.suneaststore.ui.customview.RoundImageView;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.log.LatteLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class StoreFragment extends BaseFragment {
    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_store;
    }

    private int merchId = -1;

    public StoreFragment withId(int id) {
        merchId = id;
        return this;
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.search_view)
    SearchView searchView;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.img_store)
    RoundImageView storeImg;

    @BindView(R.id.tv_store_name)
    TextView storeNameTv;

    @BindView(R.id.btn_collect_store)
    Button collectStoreBtn;

    @BindView(R.id.img_shop_manager)
    RoundImageView storeManagerImg;

    @BindView(R.id.tv_store_manager_name)
    TextView storeManagerTv;

    @BindView(R.id.banner)
    Banner banner = null;

    @BindView(R.id.tab_layout)
    TabLayout storeTab;

    TabLayout.Tab offLineTab;

    @BindView(R.id.tab_layout_cate)
    TabLayout storeCateTab;

    @BindView(R.id.rg_store)
    RadioGroup storeRg;

    @BindView(R.id.rb_finished_product)
    RadioButton finishedProductRb;

    @BindView(R.id.rv_product)
    RecyclerView productRv;
    StoreGoodsAdapter goodsAdapter;

    @BindView(R.id.layout_no_data_tip)
    LinearLayout noDataTipLayout;

    @OnClick({R.id.btn_search, R.id.btn_collect_store,
            R.id.btn_contact_shop_manager, R.id.tv_to_custom})
    public void onClickView(View view) {
        switch (view.getId()) {
            case R.id.btn_search: {
                if (keyWords.length() > 0) {
                    shouldReplace = true;
                    resetPage();
                    paramsMap.put("keyword", keyWords);
                    StoreHandler.requestGoodsList(paramsMap);
                    hideSoftInput();
                } else {
                    Toast.makeText(_mActivity, "请输入关键字", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btn_collect_store: {
                if (AccountManager.getSignState()) {
                    collectStoreBtn.setEnabled(false);
                    StoreHandler.collectStoreOrNot(merchId);
                } else {
                    Toast.makeText(_mActivity, "请登录后使用收藏功能", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btn_contact_shop_manager: {
                //todo 打开聊天界面
            }
            break;
            case R.id.tv_to_custom: {
                if (AccountManager.getSignState()) {
                    Bundle arguments = new Bundle();
                    arguments.putInt("merchid", merchId);
                    FastOrderMaker fragment = new FastOrderMaker();
                    fragment.setArguments(arguments);
                    start(fragment);
                } else {
                    Toast.makeText(_mActivity, "请登录后使用定制功能", Toast.LENGTH_SHORT).show();
                }

            }
            break;
        }
    }

    WeakHashMap<String, Object> paramsMap;
    private boolean shouldReplace = false;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        paramsMap = new WeakHashMap<>();
        initData();
        initView();
        StoreHandler.requestStorePage(merchId);
        if (AccountManager.getSignState()) {
            StoreHandler.requestStoreCollectState(merchId);
        }
    }

    private void initData() {
        paramsMap = new WeakHashMap<>();
        paramsMap.put("merchid", merchId);
        paramsMap.put("psize", 12);
        paramsMap.put("page", 1);
        paramsMap.put("sell", 1);
        paramsMap.put("type", 1);
    }

    private int curPage = 1;

    private void resetPage() {
        curPage = 1;
        paramsMap.put("page", curPage);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        banner.stopAutoPlay();
        super.onDestroyView();
    }

    private String keyWords = "";

    private void initView() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener((@NonNull RefreshLayout refreshLayout) -> {
            LatteLogger.e("test", "onRefresh");
            paramsMap.clear();
            paramsMap.put("merchid", merchId);
            paramsMap.put("psize", 12);
            paramsMap.put("page", 1);
            paramsMap.put("type", 1);
            finishedProductRb.setChecked(true);
            offLineTab.select();
            paramsMap.put("sell", 1);
            shouldReplace = true;
            resetPage();
            StoreHandler.requestStorePage(merchId);
        });
        refreshLayout.setOnLoadMoreListener((@NonNull RefreshLayout refreshLayout) -> {
            paramsMap.put("page", curPage + 1);
            StoreHandler.requestGoodsList(paramsMap);
        });

        offLineTab = storeTab.newTab().setText("线上产品");
        storeTab.addTab(offLineTab);
        storeTab.addTab(storeTab.newTab().setText("线下产品"), false);
        storeTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                LatteLogger.e("test", "onTabSelected tab = " + tab.getPosition());
                paramsMap.put("sell", tab.getPosition() + 1);
                shouldReplace = true;
                resetPage();
                StoreHandler.requestGoodsList(paramsMap);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        storeRg.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
            paramsMap.put("type", checkedId == R.id.rb_finished_product ? 1 : 2);
            shouldReplace = true;
            resetPage();
            StoreHandler.requestGoodsList(paramsMap);
            if (checkedId == R.id.rb_finished_product) {
                createCateItemTab(finishedProductBeanList);
            } else if (checkedId == R.id.rb_materials) {
                createCateItemTab(materialBeanList);
            }
        });
        storeCateTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                StoreCateBean bean = (StoreCateBean) tab.getTag();
                if (bean != null && bean.getId() != 0) {
                    paramsMap.put("cateid", bean.getId());
                } else {
                    paramsMap.remove("cateid");
                }
                shouldReplace = true;
                StoreHandler.requestGoodsList(paramsMap);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        toolbar.setNavigationOnClickListener((View v) -> {
            pop();
        });
        //搜索图标按钮(打开搜索框的按钮)的点击事件
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("test", "on search icon clicked");
            }
        });
        //搜索框文字变化监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Log.e("test", "onQueryTextChange str = " + s);
                keyWords = s;
                if (keyWords.length() == 0) {
                    paramsMap.remove("keyword");
                }
                return false;
            }
        });

        banner.setImageLoader(new GlideImageLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.isAutoPlay(true);
        banner.setDelayTime(5000);
        banner.setIndicatorGravity(BannerConfig.BOTTOM_CENTER);

        productRv.setLayoutManager(new GridLayoutManager(getContext(), 2));
        goodsAdapter = new StoreGoodsAdapter(R.layout.item_star_product);
        goodsAdapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            StoreGoodsBean bean = (StoreGoodsBean) adapter.getData().get(position);
            GoodsDetailFragment fragment = new GoodsDetailFragment().withId(bean.getId()).withMerchId(merchId);
            start(fragment);
        });
        productRv.setAdapter(goodsAdapter);
    }

    private List<StoreCateBean> finishedProductBeanList;
    private List<StoreCateBean> materialBeanList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotStoreData(GotStorePageData event) {
        refreshLayout.finishRefresh(true);
        Glide.with(_mActivity).load(event.getStoreInfoBean().getLogo()).into(storeImg);
        storeNameTv.setText(event.getStoreInfoBean().getMerchname());
        Glide.with(_mActivity).load(event.getStoreInfoBean()
                .getStore_header()).into(storeManagerImg);
        banner.setImages(event.getBannerList());
        banner.start();
        finishedProductBeanList = event.getFinishedProductCates();
        materialBeanList = event.getMaterialCates();
        createCateItemTab(finishedProductBeanList);
        goodsAdapter.setNewData(event.getStoreGoodsBeanList());
    }

    private void createCateItemTab(List<StoreCateBean> list) {
        storeCateTab.removeAllTabs();
        TabLayout.Tab tabAll = storeCateTab.newTab().setText(getString(R.string.all));
        tabAll.setTag(new StoreCateBean());
        storeCateTab.addTab(tabAll);
        for (StoreCateBean bean : list) {
            TabLayout.Tab tab = storeCateTab.newTab().setText(bean.getCatename());
            tab.setTag(bean);
            storeCateTab.addTab(tab);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotCollectResult(StoreCollectResult event) {
        collectStoreBtn.setEnabled(true);
        if (event.getResult() == Flag.Result.SUCCEED) {
            collected = event.getState() == 1;
            setCollectStoreBtn(collected);
        } else {
            Toast.makeText(_mActivity, "操作失败", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean collected = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotCollectState(GotStoreCollectState event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            collected = event.getState() == 1;
            setCollectStoreBtn(collected);
        } else {
            Toast.makeText(_mActivity, "操作失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setCollectStoreBtn(boolean isCollect) {
        if (isCollect) {
            collectStoreBtn.setText(_mActivity.getResources().getString(R.string.focused));
            collectStoreBtn.setBackground(_mActivity.getResources()
                    .getDrawable(R.drawable.corner_cb_focused));
            collectStoreBtn.setTextColor(_mActivity.getResources().getColor(R.color.yellow_darker));
        } else {
            collectStoreBtn.setText(_mActivity.getResources().getString(R.string.focus));
            collectStoreBtn.setBackground(_mActivity.getResources()
                    .getDrawable(R.drawable.corner_cb_focus));
            collectStoreBtn.setTextColor(_mActivity.getResources().getColor(R.color.white));
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotGoodsList(GotStoreGoodsList event) {
        List<StoreGoodsBean> list = event.getGoodsBeanList();
        if (list != null && list.size() > 0) {
            noDataTipLayout.setVisibility(View.GONE);
            if (shouldReplace) {
                resetPage();
                goodsAdapter.setNewData(list);
                shouldReplace = false;
            } else {
                curPage++;
                goodsAdapter.addData(list);
                refreshLayout.finishLoadMore(true);
            }
        } else {
            if (shouldReplace) {
                goodsAdapter.setNewData(new ArrayList<>());
                noDataTipLayout.setVisibility(View.VISIBLE);
                shouldReplace = false;
            }
            refreshLayout.finishLoadMore(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStoreRequestFail(StoreRequestFail event) {
        if (event.getFailType() == 0) {
            refreshLayout.finishRefresh(false);
        } else {
            refreshLayout.finishLoadMore(false);
        }
    }
}
